package com.easybuy.controller;

import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.easybuy.pojo.Order;
import com.easybuy.pojo.Order_detail;
import com.easybuy.pojo.PageBean;
import com.easybuy.pojo.Product;
import com.easybuy.pojo.Product_category;
import com.easybuy.service.OrderService;
import com.easybuy.service.Order_detailService;
import com.easybuy.service.ProductService;

import net.spy.memcached.MemcachedClient;


@Controller
@RequestMapping(value = "/product")
public class ProductController1 {

	@Autowired
	private ProductService productService;
	
	@Autowired
	OrderService orderService;
	
	@Autowired
	Order_detailService order_detailService;
	
	private static MemcachedClient mcc;
	private static Map<String, Object> nameMap;
	private static List<Integer> productId;
	static {
		try {
			 mcc = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
			 nameMap = new HashMap<String,Object>();
			 //productId = new ArrayList<Integer>();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@RequestMapping(value = "/oderList")
	@ResponseBody
	public 	Object selectOrder(@RequestParam(value = "aid",required = false)String aid,
								@RequestParam(value = "bid",required = false)String bid) {
		List<Product>  list = new ArrayList<Product>();
		list = productService.selectOrder(Integer.parseInt(aid),Integer.parseInt(bid));
		System.out.println(list);
		
		return list;
	}
	
	@RequestMapping(value = "/memberOrder")
	@ResponseBody
	public Map<String, Object> selectMemOrder(@RequestParam(required = false) String userId,
			@RequestParam(required = false) String pageNow) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> pageMap = new HashMap<String, Object>();
		PageBean<Order> pageBean = new PageBean<Order>();
		if (pageNow==null || pageNow=="") {
			pageNow="1";
		}
		pageBean.setCount(orderService.orderCount(Integer.parseInt(userId)));
		pageBean.setPageNow(Integer.parseInt(pageNow));
		pageMap.put("page", pageBean);	
		pageMap.put("userId", userId);
		List<Order> orders = orderService.selectByUserId(pageMap);
		pageBean.setList(orders);
		List<Order_detail> order_details = order_detailService.selectOrder_details();
		List<Product> products = productService.selectProducts();
		map.put("page", pageBean);
		map.put("order_details", order_details);
		map.put("products", products);
		
//		Map<Integer, List<Order_detail>> order_detailMap = new HashMap<Integer, List<Order_detail>>();
//		List<Product> products = new ArrayList<Product>();
//		Map<Integer, Integer> productIdMap = new HashMap<Integer, Integer>();
//		for (int i = 0; i < orders.size(); i++) {
//			 List<Order_detail> order_details = order_detailService.selectOrder_detailsByOrderId(orders.get(i).getId());
//			 order_detailMap.put(orders.get(i).getId(), order_details);
//			 for (Order_detail order_detail:order_details) {
//				productIdMap.put(order_detail.getProductId(), order_detail.getProductId());
//			 }
//			 
//		}
		return map;
	}
	
	@RequestMapping(value = "/orderCount")
	@ResponseBody
	public Object orderCount() {
		Integer count = productService.orderCount();
		return count;
	}

	@RequestMapping(value = "/productList")
	@ResponseBody
	public Object selectProductByPage(@RequestParam(value="pageIndex", required = false)String pageIndex) {
		
		PageBean<Product> pagebean = new PageBean<Product>();
		int count = productService.selectProductCount();
		pagebean.setCount(count);
		int pageNo= -1;
		if(pageIndex !=null && pageIndex.length()>0) {
			pageNo = Integer.parseInt(pageIndex);
		}else {
			pageNo = 1;
		}
		pagebean.setPageNow(pageNo);
		pagebean.setPageSize(8);
		int pagecount = count%8==0?count/8:count/8+1;
		pagebean.setPageCount(pagecount);
		Map<String, Object> params = new HashMap<String,Object>();
		if(!(params.containsKey("pageNow") && params.containsKey("pageSize"))) {
			params.put("pageNow", (pagebean.getPageNow()-1)*pagebean.getPageSize());
			params.put("pageSize", pagebean.getPageSize());
		}
		List<Product> products = productService.selectProductByPage(params);
		pagebean.setList(products);
		return pagebean;
	}
	
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Object deleteProduct(@RequestParam(value = "id",required = false)String id) {
		Integer pId = Integer.parseInt(id);
		Map<String, Object> resultMap = new HashMap<String,Object>();
		if(productService.deleteProduct(pId)>0) {
			resultMap.put("result", "success");
		}
		return resultMap;
	}
	//联动查询
	@RequestMapping(value = "/getType")
	@ResponseBody
	public Object selectProductType(@RequestParam(value = "id")String id) {
		Integer pId = Integer.parseInt(id);
		//System.out.println(pId);
		List<Product_category> list = productService.selectProductType(pId);
		return list;
	}
	
	@RequestMapping(value = "/getProduct")
	@ResponseBody
	public Object selectProductById(@RequestParam(value = "id",required = false)String id) {
		
		Integer pid = Integer.parseInt(id);
		Product product = productService.selectProductById(pid);
		return product;
	}
	/**
	 * 修改商品信息
	 * @param product
	 * @param attach
	 * @return
	 */
	@RequestMapping(value = "/update")
	@ResponseBody
	public Object updateProduct(@RequestParam(value = "fileName",required = false)	MultipartFile attach,
								HttpServletRequest request) {
		String fileName = null;
		Product product = new Product();
		Map<String, Object> resultMap = new HashMap<String,Object>();
		//获取参数
		Integer id = Integer.parseInt(request.getParameter("id"));
		Integer categoryLevel1Id = Integer.parseInt(request.getParameter("categoryLevel1Id"));
		Integer categoryLevel2Id = Integer.parseInt(request.getParameter("categoryLevel2Id"));
		Integer categoryLevel3Id = Integer.parseInt(request.getParameter("categoryLevel3Id"));
		String name = request.getParameter("name");
		Float price = Float.parseFloat(request.getParameter("price"));
		Integer stock = Integer.parseInt(request.getParameter("stock"));
		String description = request.getParameter("description");
		if(attach !=null){
			String path = "E:\\WebStorm\\easybuy\\images";
			String oldFileName = attach.getOriginalFilename();
			String prefix = FilenameUtils.getExtension(oldFileName);
			int filesize = 10000000;
			if(attach.getSize()>filesize){
				resultMap.put("uploadFileError", "*上传文件大小不得超过1MB");
			}else if(prefix.equalsIgnoreCase("jpg") ||
					prefix.equalsIgnoreCase("png") ||
					prefix.equalsIgnoreCase("jpeg") ||
					prefix.equalsIgnoreCase("pneg")){
				fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg";			
				File tarFile = new File(path, fileName);
				if(!tarFile.exists()){
					tarFile.mkdirs();
				}
				try {
					attach.transferTo(tarFile);
				} catch (Exception e) {
					e.printStackTrace();
					resultMap.put("uploadFileError", "* 上传失败");
				}
				//productPicPath = path+File.separator+fileName;
			}else {
				resultMap.put("uploadFileError", "* 上传图片格式不正确");
			}
		}
		product.setId(id);
		product.setCategoryLevel1Id(categoryLevel1Id);
		product.setCategoryLevel2Id(categoryLevel2Id);
		product.setCategoryLevel3Id(categoryLevel3Id);
		product.setFileName(fileName);
		product.setName(name);
		product.setPrice(price);
		product.setStock(stock);
		product.setDescription(description);
		
		if(productService.updateProduct(product)>0){
			resultMap.put("update", "success");
		}
		return resultMap;
	}
	/**
	 * 新增商品
	 * @param attach
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/addProduct")
	@ResponseBody
	public Object addProduct(@RequestParam(value = "fileName",required = false)	MultipartFile attach,
			HttpServletRequest request) {
		String fileName = null;
		Product product = new Product();
		Map<String, Object> resultMap = new HashMap<String,Object>();
		//获取参数
		
		Integer categoryLevel1Id = Integer.parseInt(request.getParameter("categoryLevel1Id"));
		Integer categoryLevel2Id = Integer.parseInt(request.getParameter("categoryLevel2Id"));
		Integer categoryLevel3Id = Integer.parseInt(request.getParameter("categoryLevel3Id"));
		String name = request.getParameter("name");
		Float price = Float.parseFloat(request.getParameter("price"));
		Integer stock = Integer.parseInt(request.getParameter("stock"));
		String description = request.getParameter("description");
		if(attach !=null){
			String path = "E:\\WebStorm\\easybuy\\images";
			String oldFileName = attach.getOriginalFilename();
			String prefix = FilenameUtils.getExtension(oldFileName);
			int filesize = 10000000;
			if(attach.getSize()>filesize){
				resultMap.put("uploadFileError", "*上传文件大小不得超过1MB");
			}else if(prefix.equalsIgnoreCase("jpg") ||
					prefix.equalsIgnoreCase("png") ||
					prefix.equalsIgnoreCase("jpeg") ||
					prefix.equalsIgnoreCase("pneg")){
				fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg";			
				File tarFile = new File(path, fileName);
				if(!tarFile.exists()){
					tarFile.mkdirs();
				}
				try {
					attach.transferTo(tarFile);
				} catch (Exception e) {
					e.printStackTrace();
					resultMap.put("uploadFileError", "* 上传失败");
				}
				//productPicPath = path+File.separator+fileName;
			}else {
				resultMap.put("uploadFileError", "* 上传图片格式不正确");
			}
		}
		product.setCategoryLevel1Id(categoryLevel1Id);
		product.setCategoryLevel2Id(categoryLevel2Id);
		product.setCategoryLevel3Id(categoryLevel3Id);
		product.setFileName(fileName);
		product.setName(name);
		product.setPrice(price);
		product.setStock(stock);
		product.setDescription(description);
		if(productService.addProduct(product)>0){
			resultMap.put("add", "success");
		}
		return resultMap;
	}
	
	
	@RequestMapping(value = "/delType")
	@ResponseBody
	public Object deleteType(@RequestParam(value = "id", required = false) String id) {
		Integer pid = Integer.parseInt(id);
		return productService.deleteType(pid);
		
	}
	
	@RequestMapping(value = "/typeList")
	@ResponseBody
	public Object selectTypeList(@RequestParam(value="pageIndex", required = false)String pageIndex) {
		PageBean<Product_category> pagebean = new PageBean<Product_category>();
		int count = productService.selectTypeCount();
		pagebean.setCount(count);
		int pageNo= -1;
		if(pageIndex !=null && pageIndex.length()>0) {
			pageNo = Integer.parseInt(pageIndex);
		}else {
			pageNo = 1;
		}
		pagebean.setPageNow(pageNo);
		pagebean.setPageSize(8);
		int pagecount = count%8==0?count/8:count/8+1;
		pagebean.setPageCount(pagecount);
		Map<String, Object> params = new HashMap<String,Object>();
		if(!(params.containsKey("pageNow") && params.containsKey("pageSize"))) {
			params.put("pageNow", (pagebean.getPageNow()-1)*pagebean.getPageSize());
			params.put("pageSize", pagebean.getPageSize());
		}
		List<Product_category> products = productService.selectProductType(params);
		pagebean.setList(products);
		return pagebean;
	}
	
	@RequestMapping(value = "/getLv1")
	@ResponseBody
	public Object selectCategoryLevel1(){
		List<Product_category> list = new ArrayList<Product_category>();
		list = productService.selectCategoryLevel1();
		return list;
	}
	
	@RequestMapping(value = "/viewType")
	@ResponseBody
	public Object selectAllType(@RequestParam(value = "id",required = false)String id) {
		Integer pid = Integer.parseInt(id);
		Product_category pc = new Product_category();
		pc = productService.selectAllType(pid);
		return pc;
	}
	
	@RequestMapping(value = "/updateType")
	@ResponseBody
	public Object updateType(Product_category pc) {
		int UpdateRows = productService.updateType(pc);
		return UpdateRows;
	}
	
	@RequestMapping(value = "/insert")
	@ResponseBody
	public Object insertNewType(Product_category pc) {
		int UpdateRows = productService.insertNewType(pc);
		return UpdateRows;
	}
	
	@RequestMapping(value = "/TypeOne")
	@ResponseBody
	public Object selectTypeOne() {
		List<Product_category> list = new ArrayList<Product_category>();
		list = productService.selectTypeOne();
		return list;
		
	}
	
	@RequestMapping(value = "/TypeTwo")
	@ResponseBody
	public Object selectTypeTwo() {
		List<Product_category> list = new ArrayList<Product_category>();
		list = productService.selectTypeTwo();
		return list;
	}
	
	@RequestMapping(value = "/collect")
	@ResponseBody
	public Object collection(@RequestParam(value = "id",required = false)String id,
							@RequestParam(value = "userName",required = false)String userName) {
		Map<String, Object> result = new HashMap<String,Object>();
		Integer pid = Integer.parseInt(id);
		//productId = new ArrayList<Integer>();
		//新用户新创建
		if(nameMap.get(userName)==null) {
			 productId = new ArrayList<Integer>();
			 productId.add(pid);
			 result.put("result", "success");
		}else {
			if(userName!=null && userName.length()>0) {
				productId = (List<Integer>) nameMap.get(userName);
				if(productId.size()==0) {
					productId.add(pid);
					result.put("result", "success");
					//nameMap.put(userName, productId);
					//mcc.set("userName", 2592000, nameMap);
				}else if(productId.size()<5){
						//确保值唯一
						if(!productId.contains(pid)) {
							productId.add(pid);
							result.put("result", "success");
						}else {
							result.put("exist", "exist");
						}
				}else {
						//确保值唯一
						if(!productId.contains(pid)) {
							productId.remove(0);
							productId.add(pid);
							result.put("result", "success");
						}else {
							result.put("exist", "exist");
						}
					
				}
			}	
		
		}
		nameMap.put(userName, productId);
		mcc.set("userName", 2592000, nameMap);						
		System.out.println(nameMap);
		System.out.println("============");
		return result;		
	}
	
	@RequestMapping(value = "/showCollect")
	@ResponseBody
	public Object showCollection(@RequestParam(value = "userName",required = false)String userName) {
		List<Product> list = new ArrayList<Product>();
		List<Integer> productId = (List) nameMap.get(userName);
		if(nameMap.containsKey(userName)) {
			for (Integer proId :productId) {
				Product product = productService.selectProductById(proId);
				list.add(product);
			}
		}
		return list;		
	}
	
	@RequestMapping( value = "/delMemId")
	@ResponseBody
	public Object delMemId(@RequestParam(value = "id",required = false)String id,
							@RequestParam(value = "userName",required = false)String userName) {
		Integer pid = Integer.parseInt(id);
		Map<String, Object> result = new HashMap<String,Object>();
		productId = (List) nameMap.get(userName);
		if(nameMap.containsKey(userName)) {
			Iterator<Integer> iter = productId.iterator();
			while(iter.hasNext()) {
				Integer item = iter.next();
				if(item.equals(pid)) {
					iter.remove();
					result.put("del", "success");
					nameMap.put(userName, productId);
					//mcc.set("id", 2592000, proList);
					System.out.println(productId);
					System.out.println("========");
					System.out.println(pid);
				}
			}
		}
		return result;
		
	}
	
}
